package com.woniuxy.controller;

import com.woniuxy.entity.RbacManager;
import com.woniuxy.entity.RbacManagerDTO;
import com.woniuxy.entity.ResponseEntity;
import com.woniuxy.service.RbacManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {
    @Autowired
    RbacManagerService rbacManagerService;
    /**
     * 登录成功后 返回token，给前端存起来
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public ResponseEntity login(String username, String password){
        //通过账号密码进行数据匹配验证，验证密码是否正确  (我不给你们提供笔记，这里自己写)
        boolean flag = rbacManagerService.verifyMyPassword(username,password);
        //flag为true说明密码是匹配的  如果账号密码正确，生成token存入redis，返回token给前端
        if (flag) {
            //生成token
            String token = rbacManagerService.sign(username, password);
            //通过用户名或密码获取rbacManager对象
            RbacManager rbacManager = rbacManagerService.findManager(username);
            //获取到token和对象以后，我们需要去把token当做value存到redis数据库中，
            // key就是我们的token value 我的manager对象
            boolean isSaved = rbacManagerService.saveTokenToRedis(token, rbacManager);
            if (isSaved){
                //redis保存成功后 含token的对象token
                RbacManagerDTO rbacManagerDTO = new RbacManagerDTO();
                rbacManager.setPassword("");
                rbacManagerDTO.setRbacManager(rbacManager);
                rbacManagerDTO.setToken(token);
                return new ResponseEntity<>(rbacManagerDTO);
            }else {
                ResponseEntity<Object> objectResponseEntity = new ResponseEntity<>();
                objectResponseEntity.setMessage("服务器维护中……");
                return objectResponseEntity;
            }
        }else{
            ResponseEntity<Object> objectResponseEntity = new ResponseEntity<>();
            objectResponseEntity.setMessage("账号或密码错误！");
            return objectResponseEntity;
        }
    }
//    @RequestMapping("/verify")
//    public String verify(String token){
//        Subject subject = SecurityUtils.getSubject();
//        subject.login(new MyJsonWebToken(token));
//        System.out.println(subject.isAuthenticated());
//        return "success";
//    }
    @RequestMapping("/401")
    public String response401(){
        return "对不起，您没有登录。";
    }
}
